package com.example.basic.web.service.newly.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.basic.web.mapper.device.DeviceMapper;
import com.example.basic.web.mapper.newly.SysFlowTaskMapper;
import com.example.basic.web.mapper.newly.SysPdaFlowMapper;
import com.example.basic.web.model.device.Device;
import com.example.basic.web.model.newly.SysFlowTask;
import com.example.basic.web.model.newly.SysPdaFlow;
import com.example.basic.web.request.IndexRequest;
import com.example.basic.web.response.IndexDeviceResponse;
import com.example.basic.web.response.IndexFireResponse;
import com.example.basic.web.response.IndexResponse;
import com.example.basic.web.response.IndexTaskResponse;
import com.example.basic.web.service.newly.ISysIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysIndexServiceImpl implements ISysIndexService {

    @Autowired
    private SysPdaFlowMapper sysPdaFlowMapper;

    @Autowired
    private SysFlowTaskMapper sysFlowTaskMapper;

    @Autowired
    private DeviceMapper deviceMapper;



    /**
     * 火化统计
     *
     * @param request
     * @return
     */
    @Override
    public IndexFireResponse fire(IndexRequest request) {
        //将开始日期和结束日期加上时间
        request.setStartDate(DateUtil.beginOfDay(request.getStartDate()));
        request.setEndDate(DateUtil.endOfDay(request.getEndDate()));

        LambdaQueryWrapper<SysPdaFlow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysPdaFlow::getFireStatus,1);
        wrapper.ge(SysPdaFlow::getFireTime,request.getStartDate());
        wrapper.le(SysPdaFlow::getFireTime,request.getEndDate());
        List<SysPdaFlow> sysPdaFlows = sysPdaFlowMapper.selectList(wrapper);
        IndexFireResponse indexFireResponse = new IndexFireResponse();
        //获取两个日期之间的所有日期
        List<DateTime> fireDate = DateUtil.rangeToList(request.getStartDate(), request.getEndDate(), DateField.DAY_OF_YEAR);
        //根据火花日期分组
        List<Long> fireNum = new ArrayList<>();
        for (DateTime dateTime : fireDate) {
            //统计该日期的火化数量
            fireNum.add(sysPdaFlows.stream().filter(sysPdaFlow -> DateUtil.format(sysPdaFlow.getFireTime(), "yyyy-MM-dd").equals(DateUtil.format(dateTime, "yyyy-MM-dd"))).count());
        }

        indexFireResponse.setFireNum(fireNum);
        return indexFireResponse;
    }

    @Override
    public List<IndexTaskResponse> task() {
        LambdaQueryWrapper<SysFlowTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysFlowTask::getEndStatus,0);
        wrapper.orderByDesc(SysFlowTask::getCreateAt);
        List<SysFlowTask> sysFlowTaskList = sysFlowTaskMapper.selectList(wrapper);
        List<IndexTaskResponse> indexTaskResponses = new ArrayList<>();
        if (!sysFlowTaskList.isEmpty()){
            for (SysFlowTask sysFlowTask : sysFlowTaskList) {
                IndexTaskResponse indexTaskResponse = new IndexTaskResponse();
                indexTaskResponse.setId(sysFlowTask.getId());
                indexTaskResponse.setNowStage(sysFlowTask.getNowStage());
                Device startDevice = deviceMapper.selectById(sysFlowTask.getStartPositionId());
                if (ObjectUtils.isNotEmpty(startDevice)){
                    indexTaskResponse.setStartPositionName(startDevice.getDeviceName());
                }
                Device endDevice = deviceMapper.selectById(sysFlowTask.getEndPositionId());
                if (ObjectUtils.isNotEmpty(endDevice)){
                    indexTaskResponse.setEndPositionName(endDevice.getDeviceName());
                }
                indexTaskResponses.add(indexTaskResponse);

            }

        }

        return indexTaskResponses;
    }

    @Override
    public IndexResponse device() {
        // 1. 查询启用的设备
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getEnableFlag, 1);
        List<Device> deviceList = deviceMapper.selectList(wrapper);

        // 2. 按设备类型分组（自动去重类型）
        Map<String, List<Device>> deviceMap = deviceList.stream()
                .collect(Collectors.groupingBy(Device::getDeviceType));

        // 3. 处理每个设备类型的统计数据
        List<IndexDeviceResponse> deviceResponses = new ArrayList<>();
        for (Map.Entry<String, List<Device>> entry : deviceMap.entrySet()) {
            String deviceType = entry.getKey();
            List<Device> devices = entry.getValue();

            IndexDeviceResponse response = new IndexDeviceResponse();
            response.setName(deviceType);
            // 总容量：该类型设备总数
            response.setTotalCapacity((long) devices.size());
            // 可用容量：状态为"1"的设备数量
            long availableCount = devices.stream()
                    .filter(device -> "1".equals(device.getStatus()))
                    .count();
            response.setAvailableCapacity(availableCount);
            // 已用容量：总数 - 可用数
            response.setUsedCapacity(response.getTotalCapacity() - availableCount);

            deviceResponses.add(response);
        }

        // 4. 按"三个一组"整理列表
        List<List<IndexDeviceResponse>> deviceListList = new ArrayList<>();
        List<IndexDeviceResponse> tempList = new ArrayList<>();

        for (int i = 0; i < deviceResponses.size(); i++) {
            tempList.add(deviceResponses.get(i));
            // 每3个元素一组，或最后不足3个时直接分组
            if ((i + 1) % 3 == 0 || i == deviceResponses.size() - 1) {
                deviceListList.add(new ArrayList<>(tempList)); // 注意创建新集合避免引用问题
                tempList.clear();
            }
        }

        // 5. 构造并返回响应
        IndexResponse indexResponse = new IndexResponse();
        indexResponse.setDeviceList(deviceListList); // 假设IndexResponse有此属性


        //统计设备数量
        long jbCount = deviceList.stream().filter(x -> x.getDevicePoint().contains("JB")).count();
        long djCount = deviceList.stream().filter(x -> x.getDevicePoint().contains("DJ")).count();
        long tsCount = deviceList.stream().filter(x -> x.getDevicePoint().contains("TS")).count();
        indexResponse.setFreezerNum(0L);
        indexResponse.setBoardTotalNum(djCount);
        indexResponse.setLiftTotalNum(tsCount);
        indexResponse.setConnectTotalNum(jbCount);


        //统计任务类型占比
        List<SysPdaFlow> sysPdaFlows = sysPdaFlowMapper.selectList(null);
        int total = sysPdaFlows.size();
        long disinfectCount = sysPdaFlows.stream().filter(x -> x.getIsDisinfect()==1).count();

        long spaCount = sysPdaFlows.stream().filter(x -> x.getIsSpa()==1).count();

        long admireCount = sysPdaFlows.stream().filter(x -> x.getIsAdmire()==1).count();

        long makeCount = sysPdaFlows.stream().filter(x -> x.getIsMake()==1).count();

        //求出比例
        BigDecimal disinfectProp = new BigDecimal(disinfectCount).divide(new BigDecimal(total), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));

        BigDecimal spaProp = new BigDecimal(spaCount).divide(new BigDecimal(total), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));


        BigDecimal admireProp = new BigDecimal(admireCount).divide(new BigDecimal(total), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        BigDecimal makeProp = new BigDecimal(makeCount).divide(new BigDecimal(total), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
        indexResponse.setDisinfectProp(disinfectProp);
        indexResponse.setSpaProp(spaProp);
        indexResponse.setLookProp(admireProp);
        indexResponse.setMakeUpProp(makeProp);

        //统计今日数据 今日入馆
        long todayEnterNum = sysPdaFlows.stream().filter(x -> x.getCreateAt().after(DateUtil.beginOfDay(new Date()))).count();
        indexResponse.setTodayEnterNum(todayEnterNum);
        //今日火化
        long todayFireNum = sysPdaFlows.stream().filter(x -> x.getFireTime()!=null && x.getFireTime().after(DateUtil.beginOfDay(new Date()))).count();
        indexResponse.setTodayFireNum(todayFireNum);
        //今日暂存
        long todayStoreNum = sysPdaFlows.stream().filter(x->x.getFireStatus()==0).count();
        indexResponse.setTodayTotalNum(todayStoreNum);
        //今日冰柜 TODO 待完善
        indexResponse.setTodayFreezerNum(0L);

        return indexResponse;
    }

    @Override
    public List<IndexDeviceResponse> deviceClassify() {
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getEnableFlag, 1);
        List<Device> deviceList = deviceMapper.selectList(wrapper);

        // 2. 按设备类型分组（自动去重类型）
        Map<String, List<Device>> deviceMap = deviceList.stream()
                .collect(Collectors.groupingBy(Device::getDeviceType));

        // 3. 处理每个设备类型的统计数据
        List<IndexDeviceResponse> deviceResponses = new ArrayList<>();
        for (Map.Entry<String, List<Device>> entry : deviceMap.entrySet()) {
            String deviceType = entry.getKey();
            List<Device> devices = entry.getValue();

            IndexDeviceResponse response = new IndexDeviceResponse();
            response.setName(deviceType);
            // 总容量：该类型设备总数
            response.setTotalCapacity((long) devices.size());
            // 可用容量：状态为"1"的设备数量
            long availableCount = devices.stream()
                    .filter(device -> "1".equals(device.getStatus()))
                    .count();
            response.setAvailableCapacity(availableCount);
            // 已用容量：总数 - 可用数
            response.setUsedCapacity(response.getTotalCapacity() - availableCount);

            deviceResponses.add(response);
        }
        return deviceResponses;
    }
}
